package com.runshu.newsmartark.util.y.sftp;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;

import java.io.File;

public class SftpUtil {
    //    private static Logger logger = LoggerFactory.getLogger(SftpUtil.class);
    String BASE_DIR;
    static boolean isUploading = false;

    /**
     * 获取Sftp对象
     *
     * @param param
     * @return
     */
    public static SftpConfig getSftpObj(String param) {
        SftpConfig sftpConfig = new SftpConfig();
        if (!TextUtils.isEmpty( param )) {
            sftpConfig = (SftpConfig) new Gson().fromJson( param, SftpConfig.class );
        }
        return sftpConfig;
    }

    /**
     * sftp 上传
     */
    public static boolean upload(SftpConfig config, String baseDir, String fileName, String filePath) {
        if (isUploading) return false;
        isUploading = true;
        Log.v( "sftp", "路径：baseDir=" + baseDir );
        SftpChannel sftpChannel = new SftpChannel();
        ChannelSftp sftp = null;
        try {
            if (!TextUtils.isEmpty( config.getPrivateKeyPath() )) {
                sftp = sftpChannel.connectByIdentity( config );
            } else {
                sftp = sftpChannel.connectByPwd( config );
            }
            if (sftp.isConnected()) {
                Log.v( "sftp", "连接服务器成功" );
            } else {
                Log.e( "sftp", "连接服务器失败" );
                isUploading = false;
                return false;
            }
            //检查路径
            if (!isExist( sftp, baseDir )) {
                Log.e( "sftp", "创建sftp服务器路径失败:" + baseDir );
                isUploading = false;
                return false;
            }
            String dst = baseDir + "/" + fileName;
            String src = filePath + "/" + fileName;
            File srcFile = new File( src );
            if (!srcFile.exists()) {
                Log.v( "sftp", "没有更新的日志，无须上传" );
                isUploading=false;
                return true;
            }
            Log.v( "sftp", "开始上传，本地服务器路径：[" + src + "]目标服务器路径：[" + dst + "]" );
            sftp.put( src, dst, ChannelSftp.APPEND );
            Log.v( "sftp", "上传成功" );
            if (srcFile.exists()) srcFile.delete();
            isUploading = false;
            return true;
        } catch (Exception e) {
            Log.e( "sftp", "上传失败", e );
            isUploading = false;
            return false;
        } finally {
            sftpChannel.closeChannel();
        }
    }

    /**
     * sftp 下载
     */
    public static boolean down(SftpConfig config, String baseDir, String fileName1, String filePath, String fileName2) {
        SftpChannel sftpChannel = new SftpChannel();
        ChannelSftp sftp = null;
        try {
            if (!TextUtils.isEmpty( config.getPrivateKeyPath() )) {
                sftp = sftpChannel.connectByIdentity( config );
            } else {
                sftp = sftpChannel.connectByPwd( config );
            }
            if (sftp.isConnected()) {
                Log.v( "sftp", "连接服务器成功" );
            } else {
                Log.e( "sftp", "连接服务器失败" );
                return false;
            }
            String dst = "";
            if (TextUtils.isEmpty( fileName2 )) {
                dst = filePath + fileName1;
            } else {
                dst = filePath + fileName2;
            }
            String src = baseDir + "/" + fileName1;
            Log.v( "sftp", "开始下载，sftp服务器路径：[" + src + "]目标服务器路径：[" + dst + "]" );
            sftp.get( src, dst );
            Log.v( "sftp", "下载成功" );
            return true;
        } catch (Exception e) {
            Log.e( "sftp", "下载失败", e );
            return false;
        } finally {
            sftpChannel.closeChannel();
        }
    }

    /**
     * 判断文件夹是否存在
     * true 目录创建成功，false 目录创建失败
     *
     * @param sftp
     * @param filePath 文件夹路径
     * @return
     */
    public static boolean isExist(ChannelSftp sftp, String filePath) {
        String paths[] = filePath.split( "\\/" );
        String dir = paths[0];
        for (int i = 0; i < paths.length - 1; i++) {
            dir = dir + "/" + paths[i + 1];
            try {
                sftp.cd( dir );
            } catch (SftpException sException) {
                if (sftp.SSH_FX_NO_SUCH_FILE == sException.id) {
                    try {
                        sftp.mkdir( dir );
                    } catch (SftpException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
